<template>
  <section>
    <a-card size="small">
      <template #title v-if="titles">
        <section class="file-title">
          <span class="mr-5">附件信息</span>
          (
          <a-breadcrumb>
            <a-breadcrumb-item
                class="crumb-item"
                v-for="(crumb, index) of crumbList"
                :key="crumb.key"
                @click="handleCrumbItemClick(crumb, index)"
                :class="crumb.key == currentCrumb.key ? 'active' : ''"
            >
              {{ crumb.title }}
            </a-breadcrumb-item>
          </a-breadcrumb>
          )
        </section>
      </template>
      <template #extra v-if="showOption">
        <a-dropdown :trigger="['click']" :disabled="disabled">
          <a-button>
            <template #icon>
              <PlusOutlined/>
            </template>
            添加附件
          </a-button>
          <template #overlay>
            <a-menu>
              <a-menu-item v-if="addfolder" key="new_folder" @click="addAttachment(1)">
                新建文件夹
              </a-menu-item>
              <a-menu-item v-if="uploadfiles" key="new_file" @click="addAttachment(2)">
                上传文件
              </a-menu-item>
              <a-menu-item v-if="batchupload" key="new_file" @click="addAttachment(3)">
                <a-upload
                    name="file"
                    v-model:fileList="fileList"
                    :action="$utils.fileAction"
                    :headers="{ 'org-token': $store.getters.token }"
                    multiple
                    :showUploadList="false"
                    accept=".doc,.docx,.pdf,.jpg,.jpeg,.png"
                    :data="{ dir: 'org_contract_add_attachments' }"
                    @change="handleChange"
                >
                  批量上传
                </a-upload>
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </template>
      <a-table
          :dataSource="dataList"
          :columns="columns"
          rowKey="id"
          :loading="loading"
          :pagination="pagination"
          @change="handleTableChange"
          size="small"
          bordered
      >
        <template #bodyCell="{ text, record, index, column }">
          <template v-if="column.key === 'name'">
            <div class="file-name" @click="handleNameClick(record)">
              <FolderOutlined v-if="record.annex_type == 1"/>
              <FileOutlined v-if="record.annex_type == 2"/>
              <span class="name">{{ text }}</span>
            </div>
          </template>

          <template v-if="column.key === 'action'">
            <a-tooltip>
              <template #title>在线预览</template>
              <a-button
                type="link"
                :disabled="record.online_preview && !record.online_preview.previewUrl &&
                  record.online_preview.documentType !== 'pic'
                "
                @click="previewClick(record)"
              >
                <template #icon>
                  <EyeOutlined v-if="record.annex_type == 2"/>
                </template>
              </a-button>
            </a-tooltip>
            <a-space v-if="record.operate && record.operate.length">
              <a-tooltip v-if="record.operate.includes('Topping')">
                <template #title>置顶</template>
                <a-button
                    type="link"
                    @click="fileToTop(text)"
                    :disabled="disabled"
                >
                  <template #icon>
                    <ToTopOutlined/>
                  </template>
                </a-button>
              </a-tooltip>
              <a-tooltip v-if="record.operate.includes('Download')">
                <template #title>下载</template>
                <a-button type="link" @click="downloadFile(record.file_path)">
                  <template #icon>
                    <DownloadOutlined/>
                  </template>
                </a-button>
              </a-tooltip>
              <a-tooltip v-if="showOption && record.operate.includes('Delete')">
                <template #title>删除</template>
                <a-button
                    type="link"
                    danger
                    @click="deleteFile(text)"
                    :disabled="disabled"
                >
                  <template #icon>
                    <DeleteOutlined/>
                  </template>
                </a-button>
              </a-tooltip>
            </a-space>
            <span v-else>--</span>
          </template>
        </template>
      </a-table>
    </a-card>
    <add-attachments
        :params="addParams"
        :visible="addVisible"
        @cancel="addVisible = false"
        @success="handleAddSuccess"
    />
    <!-- 合同预览 -->
    <electronContractModal
        :visible="electronContractVisible"
        :esignDetail="{
        esignCheck: true,
      }"
        @close="electronContractVisible = false"
        @refresh="electronContractVisible = false"
        type="contractDetail"
        title="在线预览"
        :urlData="previewUrlData"
    />

    <!-- 预览图片 -->
    <PreviewImg
        :visible="imgVisible"
        :index="0"
        :list="imgList"
        @close="imgVisible = false"
    />

    <MultipleAddAttachments :visible="multiAddVisible" :file-list="fileList"
                            @handleCancel="handleCancel"
                            :params="addParams"
                            @handleCommit="handleAddSuccess"/>
  </section>
</template>

<script>
import {defineComponent, ref, watch, computed, reactive} from "vue";
import {
  PlusOutlined,
  ToTopOutlined,
  FolderOutlined,
  FileOutlined,
  DownloadOutlined,
  DeleteOutlined,
  EyeOutlined,
} from "@ant-design/icons-vue";
import addAttachments from "./modules/AddAttachments.vue";
import utils from "../../../common/utils/utils";
import request from "../../../common/utils/request";
import {message} from "ant-design-vue";
import {useRoute} from "vue-router";
import electronContractModal from "../../../components/ElectronContractModal/index.vue";
import {PreviewImg} from "bl-common-vue3";
import MultipleAddAttachments from "./modules/MultipleAddAttachments.vue";


export default defineComponent({
  name: "ContractAttachmentInfo",
  components: {
    PlusOutlined,
    ToTopOutlined,
    FolderOutlined,
    FileOutlined,
    addAttachments,
    DownloadOutlined,
    DeleteOutlined,
    EyeOutlined,
    electronContractModal,
    PreviewImg,
    MultipleAddAttachments
  },
  props: {
    active: {
      type: Boolean,
      default: false,
    },
    // contract_id, object_id
    params: {
      type: Object,
      default: () => {
        return {};
      },
    },
    // contract, bill
    typeFrom: {
      type: String,
      default: "contract",
    },
    showOption: {
      type: Boolean,
      default: true,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    showType: {
      type: String,
      default: "",
    },
    drawerId: {
      type: [Number, String],
      default: "",
    },
    addfolder: {
      type: Boolean,
      default: true,
    },
    uploadfiles: {
      type: Boolean,
      default: true,
    },
    batchupload: {
      type: Boolean,
      default: true,
    },
    object: {
      type: Boolean,
      default: true,
    },
    titles: {
      type: Boolean,
      default: true,
    },
  },
  setup(props, context) {
    const route = useRoute();

    const homeCrumb = {key: "home", parentId: 0, title: "首页"};
    const crumbList = ref([homeCrumb]);
    const currentCrumb = ref(homeCrumb);
    const id = computed(() => props.showType === "drawer" ? Number(props.drawerId) : Number(route.query.id) );
    // 点击面包屑
    const handleCrumbItemClick = (crumb, index) => {
      if (currentCrumb.value.key == crumb.key) {
        return;
      }
      currentCrumb.value = crumb;
      crumbList.value.splice(index + 1, crumbList.value.length - index - 1);
      getDataList();
    };

    // 点击进入文件夹
    const handleNameClick = (record) => {
      if (record.annex_type == 1) {
        let item = {
          key: "sub_" + record.id,
          parentId: record.id,
          title: record.name,
        };
        crumbList.value.push(item);
        currentCrumb.value = item;
        getDataList();
      }
    };

    // 添加文件、文件夹
    const addVisible = ref(false);
    //批量上传
    const multiAddVisible = ref(false);
    const fileList = ref([]);
    const handleAddSuccess = () => {
      fileList.value = []
      multiAddVisible.value = false;
      addVisible.value = false;
      page.value = 1;
      getDataList();
    };
    const addAttachment = (type) => {
      addParams.value = {
        objectId: attachParams.object_id,
        annex_type: type,
        parent_id: currentCrumb.value.parentId,
        ...attachParams,
        typeFrom: props.typeFrom,
      };
      if (type != 3) {
        addVisible.value = true;
      }
    };

    const handleChange = (info) => {
      fileList.value = info.fileList
      multiAddVisible.value = true;
      console.log(fileList.value)
    }
    const handleCancel = () => {
      fileList.value = []
      multiAddVisible.value = false;
    };


    // 附件列表
    const page = ref(1);
    const limit = ref(10);
    const total = ref(0);
    const pagination = computed(() => ({
      total: total.value,
      current: page.value,
      pageSize: limit.value,
      showSizeChanger: true,
    }));
    const loading = ref(false);
    const handleTableChange = (pager, filters, sorter) => {
      page.value = pager.current;
      limit.value = pager.pageSize;
    };
    watch([page, limit], () => {
      getDataList();
    });
    const addParams = ref({});
    const dataList = ref([]);
    const getDataList = () => {
      let params = {
        parent_id: currentCrumb.value.parentId,
        page: page.value,
        limit: limit.value,
        ...attachParams,
      };
      request
          .get("/org", `/${props.typeFrom}/annexList`, params)
          .then((res) => {
            dataList.value = res.list;
            total.value = res.total;
          });
    };

    // 文件置顶
    const fileToTop = (id) => {
      const params = {
        id,
        needMsg: true,
      };
      if (attachParams.type) {
        params.type = attachParams.type;
      }
      request.put("/org", `/${props.typeFrom}/annexTop`, params).then((res) => {
        getDataList();
        message.success(res.msg || "置顶成功");
      });
    };

    // 下载文件
    const downloadFile = (url) => {
      if (!url) {
        message.error("未返回文件路径，无法下载");
        return;
      }
      window.open(url);
    };

    // 删除文件
    const deleteFile = (id) => {
      utils.modalConfirm({
        content:
            "确认删除此文件或文件夹（删除文件夹则该文件夹目录下的文件将全部删除）？",
        onOk: () => {
          const params = {
            id,
            needMsg: true,
          };
          if (attachParams.type) {
            params.type = attachParams.type;
          }
          request
              .del("/org", `/${props.typeFrom}/annexDel`, params)
              .then((res) => {
                getDataList();
                message.success(res.msg || "删除成功");
              });
        },
      });
    };

    const randomStr = utils.getRandomUid(18);
    let loaded = false;

    let attachParams = {};

    // 在线预览
    const imgVisible = ref(false);
    const imgList = ref([]);
    const electronContractVisible = ref(false);
    const previewUrlData = ref({});
    const previewClick = (record) => {
      if (record.online_preview) {
        if (record.online_preview.documentType == "word") {
          previewUrlData.value = {
            url: record.file_path,
            previewUrl: record.online_preview.previewUrl,
          };
          electronContractVisible.value = true;
          return;
        }
        if (record.online_preview.documentType == "pic") {
          imgList.value = [record.file_path];
          imgVisible.value = true;
        }
      }
      if (record.file_path.indexOf('.jpg') != -1 || record.file_path.indexOf('.jpeg') != -1 || record.file_path.indexOf('.png') != -1) {
        imgList.value = [record.file_path];
        imgVisible.value = true;
      }
    };

    const init = () => {
      if (
          loaded ||
          (props.typeFrom == "contract" && id.value && !props.params.contract_id && props.object)
      ) {
        return;
      }
      attachParams = {};
      attachParams = {...props.params};
      if (!attachParams.object_id) {
        attachParams.object_id = randomStr;
        context.emit("getObjectId", randomStr);
      }
      console.log("attachParams", attachParams);
      getDataList();
      loaded = true;
    };

    init();

    watch(
        () => props.active,
        (val) => {
          if (val) {
            init();
          }
        }
    );

    watch(
        () => props.params,
        (params) => {
          if (params && Object.keys(params).length) {
            loaded = false;
            init();
          }
        },
        {deep: true}
    );

    return {
      crumbList,
      columns,
      dataList,
      currentCrumb,
      addVisible,
      pagination,
      loading,
      addParams,
      handleCrumbItemClick,
      handleNameClick,
      handleAddSuccess,
      addAttachment,
      handleTableChange,
      fileToTop,
      deleteFile,
      downloadFile,
      previewClick,
      electronContractVisible,
      previewUrlData,

      imgList,
      imgVisible,
      handleChange,
      multiAddVisible,
      fileList,
      handleCancel,
    };
  },
});
const columns = [
  {
    title: "文件名",
    dataIndex: "name",
    key: "name",
  },
  {
    title: "操作人",
    dataIndex: "operate_user",
    key: "operate_user",
  },
  {
    title: "操作时间",
    dataIndex: "operate_time",
    key: "operate_time",
  },
  {
    title: "操作",
    dataIndex: "id",
    key: "action",
  },
];
</script>

<style lang="less" scoped>
.file-title {
  display: flex;
  align-items: center;

  .crumb-item {
    padding: 0 4px;
    cursor: pointer;
  }

  .active {
    color: @primary-color;
  }
}

.file-name {
  font-size: 16px;
  color: @primary-color;
  cursor: pointer;

  .name {
    margin-left: 8px;
  }
}
</style>
